﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BbsbWebService.Classes;
using System.Threading;
using BbsbWebService.Service;
using BbsbWebService.Classes.Controllers;
using BbsbWebService.Classes.Plugins.Bbsb;

namespace BbsbWebService
{
    public static class ApplicationState
    {
        static BbsbService _service;
        
        public static bool IsHuntingForServer { get; set; }

        public static bool IsConnectedToClient { get; set; }

        public static ServerItem LocalMachine
        {
            get
            {
                return new ServerItem
                {
                    ComputerName = Environment.MachineName,
                    Port = AppSettings.Instance.Port
                };
            }
        }

        public static ServerItem ServerMachine { get; set; }

        public static bool IsClient
        {
            get
            {
                return ServerMachine != null;
            }
        }

        public static void SniffForServer()
        {
            var bbsbController = AllControllers.GetController<BbsbController>();
            if (bbsbController != null)
            {
                bbsbController.Listen();
                ApplicationState.IsHuntingForServer = true;
                bbsbController.SendRequest();
                DateTime now = DateTime.Now;
                while (DateTime.Now - now < TimeSpan.FromSeconds(2) && !ApplicationState.IsClient) { Thread.Sleep(10); }
                ApplicationState.IsHuntingForServer = false;
                IsConnectedToClient = IsClient;
                BbsbController.Listening = false;;
            }
        }

        public static void StartService()
        {
            _service = new BbsbService();
            _service.Initialise(new Uri(ApplicationState.LocalMachine.ToBbsbServiceAddress()));
            AllControllers.Listen();
        }
     
        public static void StopService()
        {
            AllControllers.StopListening();
            _service.StopService();
        }
    }
}
